package com.beidasoft.web.util.encrypt.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONUtil;
import com.beidasoft.web.util.SMUtil;
import com.beidasoft.web.util.StringUtility;
import com.beidasoft.web.util.encrypt.service.BDPEncryptStrategyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

/**
 * @Author zhangwj1
 * @Description TODO
 * @date 2022/10/9 10:23
 * @Version 1.0
 */
@Service("AES")
public class AESServiceImpl implements BDPEncryptStrategyService {
    private final String key = "1e8fad585f08c4f44649ca626a7696cc";
    @Resource(
            name = "RSA"
    )
    private BDPEncryptStrategyService resService;

    public AESServiceImpl() {
    }

    public Object getKey() {
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        return SMUtil.byteToHex(key);
    }

    public String encrypt(String content) {
        return this.encrypt(content, this.key);
    }

    public String encrypt(String content, String encryptKey) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, encryptKey.getBytes());
        byte[] encrypt = aes.encrypt(content);
        return Base64.getEncoder().encodeToString(encrypt);
    }

    public String decrypt(String encryptStr) {
        return this.decrypt(encryptStr, this.key);
    }

    public String decrypt(String encryptStr, String decryptKey) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, decryptKey.getBytes());
        byte[] decrypt = aes.decrypt(encryptStr);
        return new String(decrypt);
    }

    public String decrypt(HttpServletRequest request, String encryptedData, Boolean contentTypeByJson, String requestPostStr) {
        String encryptKey = null;
        String encryptedSecret = "encryptedSecret";
        if (contentTypeByJson) {
            if (requestPostStr != null && requestPostStr.contains(encryptedSecret)) {
                Object enyData = JSONUtil.parseObj(requestPostStr).get(encryptedSecret);
                encryptKey = StringUtility.isNullOrEmpty(enyData) ? null : String.valueOf(enyData);
            }
        } else {
            encryptKey = request.getParameter(encryptedSecret);
        }

        String decrypt = this.resService.decrypt(encryptKey);
        AES aes = SecureUtil.aes(decrypt.getBytes());
        return aes.decryptStr(encryptedData, CharsetUtil.CHARSET_UTF_8);
    }
}

